﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.UI;
using Medianamik.Core.Sugar;
using Medianamik.Core;
using Medianamik.Core.Security;
using Medianamik.UI.Controls;

namespace Medianamik.UI.TypeManagement
{
    public partial class SecurityManagement : BaseTypePage
    {

        #region Fields

        private Guid _typeID;  //Param obligatoire

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            //Param obligatoire
            #region Param TypeID

            if (!StringHelper.IsGuid(Request.QueryString[DefaultParamNames.TypeID], out _typeID) || CurrentType == null)
            {
                Response.Redirect(ReturnURL);
            }

            #endregion

            if (!IsPostBack)
            {
                LoadPermissions();
            }
        }

        protected void SavePermissions(object sender, EventArgs e)
        {
            SecurityManager.ApplyPermissionsToType(CurrentType, typePermissionSelector.Permissions);

            Response.Redirect(ReturnURL);
        }

        #endregion

        #region Properties

        private NodeType _currentType;
        public NodeType CurrentType
        {
            get
            {
                if (_currentType == null)
                {
                    _currentType = NodeTypeManager.GetNodeType(_typeID);
                }

                return _currentType;
            }
        }

        private string _returnURL;
        public string ReturnURL
        {
            get
            {
                if (_returnURL == null)
                {
                    if (CameFromSearchPage)
                    {
                        _returnURL = SearchURL;
                    }
                    else
                    {
                        _returnURL = "TypeList.aspx";

                        if (CurrentType != null && CurrentType.ParentID.HasValue)
                        {
                            _returnURL += "?basetypeid=" + CurrentType.ParentID;
                        }
                    }
                }
                return _returnURL;
            }
        }

        #endregion

        #region Methods

        private void LoadPermissions()
        {
            typePermissionSelector.SecuredObjectId = _typeID;
            typePermissionSelector.DataBind();
        }

        #endregion

    }
}
